package cn.sylinx.horm.proxy.mapper.registrar;

import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

import cn.sylinx.horm.proxy.ProxyObjectRegistry;
import cn.sylinx.horm.proxy.mapper.parse.MapperParser;
import cn.sylinx.horm.proxy.mapper.parse.Namespace;
import cn.sylinx.horm.proxy.mapper.parse.NamespaceContainer;
import cn.sylinx.horm.resource.io.MapperXmlScanner;
import cn.sylinx.horm.resource.io.Resources;
import cn.sylinx.horm.util.GLog;
import cn.sylinx.horm.util.StrKit;

public class DefaultMapperRegistrar implements MapperRegistrar {

    static final MapperRegistrar DEFAULT_MR = new DefaultMapperRegistrar();

    @Override
    public void register(String mapperScanPackage, String matchedPostfix) {

        // Mapper 扫描包，如果为空，则全项目扫描
        if (StrKit.isBlank(mapperScanPackage)) {
            // mapperScanPackage
            GLog.warn("horm.config.mapper-scan-package没有配置，这将导致花费更多时间扫描整个项目");
        }

        String pkgInfo = StrKit.isBlank(mapperScanPackage) ? "整个项目" : mapperScanPackage;
        GLog.info("扫描包:{}, 寻找Mapper对象", pkgInfo);

        int count = 0;

        MapperXmlScanner xml = new MapperXmlScanner(mapperScanPackage, matchedPostfix);

        Set<Object> xmlSets = xml.scan(true);

        for (Object xmlObject : xmlSets) {

            InputStream xmlIs = null;
            try {
                xmlIs = Resources.getResourceAsStream(xmlObject.toString());
            } catch (IOException e) {
                GLog.error("get mapper resource[" + xmlObject + "] error:" + e.getMessage(), e);
            }
            if (xmlIs == null) {
                continue;
            }

            Namespace ns = MapperParser.create().parse(xmlIs);
            if (ns == null) {
                GLog.error("get mapper resource[" + xmlObject + "] error");
                continue;
            }

            // 保持mapper元数据
            NamespaceContainer.register(ns);
            // 注册代理类
            ProxyObjectRegistry.INSTANCE.register(ns.getMapperClass());
            count++;
        }

        GLog.info("扫描包:{}，寻找Mapper对象完毕，总计:{}", pkgInfo, count);

    }

}
